#coding=utf-8
#Boa:FramePanel:PanelSaleList

import wx

import DlgCustomerChoice
import DlgPopupSupplier

from product import *
from ctrlAider import *
from MyListCtrl import *

from wx.lib.splitter import MultiSplitterWindow
from permitManager import PermitManager

[wxID_PANELSALELIST, wxID_PANELSALELISTBTNAFTERSETTLE, 
 wxID_PANELSALELISTBTNALLDATE, wxID_PANELSALELISTBTNCLEAR, 
 wxID_PANELSALELISTBTNDAYAFTER, wxID_PANELSALELISTBTNDAYBEFORE, 
 wxID_PANELSALELISTBTNEXPORTLIST, wxID_PANELSALELISTBTNONEDAY, 
 wxID_PANELSALELISTBTNONEMONTH, wxID_PANELSALELISTBTNONEWEEK, 
 wxID_PANELSALELISTBTNONEYEAR, wxID_PANELSALELISTBTNPOPUPPEER, 
 wxID_PANELSALELISTBTNPRINT, wxID_PANELSALELISTBTNSEARCH, 
 wxID_PANELSALELISTCBORDERTYPE, wxID_PANELSALELISTCHECKBOX_NOT_DELIVERY, 
 wxID_PANELSALELISTCHECKBOX_UNPAID, wxID_PANELSALELISTCOMBOBOXPIONEER, 
 wxID_PANELSALELISTDATEEND, wxID_PANELSALELISTDATESTART, 
 wxID_PANELSALELISTSTATICTEXT1, wxID_PANELSALELISTTCPEERNAME, 
 wxID_PANELSALELISTTDATE, wxID_PANELSALELISTTPEER, 
] = [wx.NewId() for _init_ctrls in range(24)]

[Type_Sale, Type_Pur] = [0,1]

class PanelSaleList(wx.Panel):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PANELSALELIST, name=u'PanelSaleList',
              parent=prnt, pos=wx.Point(655, 215), size=wx.Size(1059, 707),
              style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(1043, 669))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False, u'Arial'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.TPeer = wx.StaticText(id=wxID_PANELSALELISTTPEER,
              label=u'\u5355\u4f4d\u540d\u79f0\uff1a', name=u'TPeer',
              parent=self, pos=wx.Point(22, 70), size=wx.Size(85, 19), style=0)

        self.TDate = wx.StaticText(id=wxID_PANELSALELISTTDATE,
              label=u'\u67e5\u8be2\u65e5\u671f\uff1a', name=u'TDate',
              parent=self, pos=wx.Point(22, 38), size=wx.Size(85, 19), style=0)
        self.TDate.SetAutoLayout(True)
        self.TDate.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'Arial'))

        self.dateStart = wx.DatePickerCtrl(id=wxID_PANELSALELISTDATESTART,
              name=u'dateStart', parent=self, pos=wx.Point(126, 30),
              size=wx.Size(120, 27), style=wx.DP_DROPDOWN)
        self.dateStart.SetLabel(u'2014-04-24')
        self.dateStart.SetValue(wx.DateTimeFromDMY(24, 3, 2014, 0, 0, 0))
        self.dateStart.SetToolTipString(u'dateStart')

        self.tcPeerName = wx.TextCtrl(id=wxID_PANELSALELISTTCPEERNAME,
              name=u'tcPeerName', parent=self, pos=wx.Point(126, 64),
              size=wx.Size(250, 28), style=0, value=u'')

        self.staticText1 = wx.StaticText(id=wxID_PANELSALELISTSTATICTEXT1,
              label=u'\u81f3', name='staticText1', parent=self,
              pos=wx.Point(254, 38), size=wx.Size(18, 18), style=0)

        self.dateEnd = wx.DatePickerCtrl(id=wxID_PANELSALELISTDATEEND,
              name=u'dateEnd', parent=self, pos=wx.Point(278, 30),
              size=wx.Size(116, 27), style=wx.DP_DROPDOWN)

        self.btnOneDay = wx.Button(id=wxID_PANELSALELISTBTNONEDAY,
              label=u'\u5f53\u65e5', name=u'btnOneDay', parent=self,
              pos=wx.Point(402, 30), size=wx.Size(46, 29), style=0)
        self.btnOneDay.Bind(wx.EVT_BUTTON, self.OnBtnOneDayButton,
              id=wxID_PANELSALELISTBTNONEDAY)

        self.btnOneWeek = wx.Button(id=wxID_PANELSALELISTBTNONEWEEK,
              label=u'\u4e00\u5468', name=u'btnOneWeek', parent=self,
              pos=wx.Point(450, 30), size=wx.Size(46, 29), style=0)
        self.btnOneWeek.Bind(wx.EVT_BUTTON, self.OnBtnOneWeekButton,
              id=wxID_PANELSALELISTBTNONEWEEK)

        self.btnOneMonth = wx.Button(id=wxID_PANELSALELISTBTNONEMONTH,
              label=u'\u4e00\u6708', name=u'btnOneMonth', parent=self,
              pos=wx.Point(498, 30), size=wx.Size(46, 29), style=0)
        self.btnOneMonth.Bind(wx.EVT_BUTTON, self.OnBtnOneMonthButton,
              id=wxID_PANELSALELISTBTNONEMONTH)

        self.btnOneYear = wx.Button(id=wxID_PANELSALELISTBTNONEYEAR,
              label=u'\u4e00\u5e74', name=u'btnOneYear', parent=self,
              pos=wx.Point(546, 30), size=wx.Size(46, 29), style=0)
        self.btnOneYear.Bind(wx.EVT_BUTTON, self.OnBtnOneYearButton,
              id=wxID_PANELSALELISTBTNONEYEAR)

        self.btnAllDate = wx.Button(id=wxID_PANELSALELISTBTNALLDATE,
              label=u'\u5168\u90e8', name=u'btnAllDate', parent=self,
              pos=wx.Point(594, 30), size=wx.Size(46, 29), style=0)
        self.btnAllDate.Bind(wx.EVT_BUTTON, self.OnBtnAllDateButton,
              id=wxID_PANELSALELISTBTNALLDATE)

        self.btnSearch = wx.Button(id=wxID_PANELSALELISTBTNSEARCH,
              label=u'\u67e5\u8be2', name=u'btnSearch', parent=self,
              pos=wx.Point(424, 64), size=wx.Size(72, 29), style=0)
        self.btnSearch.Bind(wx.EVT_BUTTON, self.OnBtnSearchButton,
              id=wxID_PANELSALELISTBTNSEARCH)

        self.btnPopupPeer = wx.Button(id=wxID_PANELSALELISTBTNPOPUPPEER,
              label=u'+', name=u'btnPopupPeer', parent=self, pos=wx.Point(376,
              64), size=wx.Size(24, 29), style=0)
        self.btnPopupPeer.Bind(wx.EVT_BUTTON, self.OnBtnPopupPeerButton,
              id=wxID_PANELSALELISTBTNPOPUPPEER)

        self.btnExportList = wx.Button(id=wxID_PANELSALELISTBTNEXPORTLIST,
              label=u'\u5bfc\u51fa\u5f53\u524d\u6570\u636e\u5230EXCEL',
              name=u'btnExportList', parent=self, pos=wx.Point(584, 64),
              size=wx.Size(195, 29), style=0)
        self.btnExportList.Bind(wx.EVT_BUTTON, self.OnBtnExportListButton,
              id=wxID_PANELSALELISTBTNEXPORTLIST)

        self.btnPrint = wx.Button(id=wxID_PANELSALELISTBTNPRINT,
              label=u'\u6253\u5370\u5355\u636e', name=u'btnPrint', parent=self,
              pos=wx.Point(504, 64), size=wx.Size(80, 29), style=0)
        self.btnPrint.Bind(wx.EVT_BUTTON, self.OnBtnPrintButton,
              id=wxID_PANELSALELISTBTNPRINT)

        self.btnDayBefore = wx.Button(id=wxID_PANELSALELISTBTNDAYBEFORE,
              label=u'\u524d\u4e00\u5929', name=u'btnDayBefore', parent=self,
              pos=wx.Point(656, 30), size=wx.Size(64, 29), style=0)
        self.btnDayBefore.Bind(wx.EVT_BUTTON, self.OnBtnDayBeforeButton,
              id=wxID_PANELSALELISTBTNDAYBEFORE)

        self.btnDayAfter = wx.Button(id=wxID_PANELSALELISTBTNDAYAFTER,
              label=u'\u540e\u4e00\u5929', name=u'btnDayAfter', parent=self,
              pos=wx.Point(720, 30), size=wx.Size(64, 29), style=0)
        self.btnDayAfter.Bind(wx.EVT_BUTTON, self.OnBtnDayAfterButton,
              id=wxID_PANELSALELISTBTNDAYAFTER)

        self.checkBox_unpaid = wx.CheckBox(id=wxID_PANELSALELISTCHECKBOX_UNPAID,
              label=u'\u672a\u4ed8\u6b3e', name=u'checkBox_unpaid', parent=self,
              pos=wx.Point(792, 40), size=wx.Size(109, 19), style=0)
        self.checkBox_unpaid.SetValue(False)
        self.checkBox_unpaid.Bind(wx.EVT_CHECKBOX,
              self.OnCheckBox_unpaidCheckbox,
              id=wxID_PANELSALELISTCHECKBOX_UNPAID)

        self.checkBox_not_delivery = wx.CheckBox(id=wxID_PANELSALELISTCHECKBOX_NOT_DELIVERY,
              label=u'\u4e0d\u663e\u793a\u76f4\u9001\u5355',
              name=u'checkBox_not_delivery', parent=self, pos=wx.Point(648, 8),
              size=wx.Size(128, 19), style=0)
        self.checkBox_not_delivery.SetValue(False)
        self.checkBox_not_delivery.Show(False)
        self.checkBox_not_delivery.Bind(wx.EVT_CHECKBOX,
              self.OnCheckBox_not_deliveryCheckbox,
              id=wxID_PANELSALELISTCHECKBOX_NOT_DELIVERY)

        self.comboBoxPioneer = wx.ComboBox(choices=[],
              id=wxID_PANELSALELISTCOMBOBOXPIONEER, name=u'comboBoxPioneer',
              parent=self, pos=wx.Point(936, 64), size=wx.Size(100, 27),
              style=0, value=u'')
        self.comboBoxPioneer.SetLabel(u'')

        self.btnClear = wx.Button(id=wxID_PANELSALELISTBTNCLEAR, label=u'x',
              name=u'btnClear', parent=self, pos=wx.Point(400, 64),
              size=wx.Size(24, 29), style=0)
        self.btnClear.Bind(wx.EVT_BUTTON, self.OnBtnClearButton,
              id=wxID_PANELSALELISTBTNCLEAR)

        self.btnAfterSettle = wx.Button(id=wxID_PANELSALELISTBTNAFTERSETTLE,
              label=u'\u5f52\u7ed3\u540e', name=u'btnAfterSettle', parent=self,
              pos=wx.Point(936, 32), size=wx.Size(86, 29), style=0)
        self.btnAfterSettle.Bind(wx.EVT_BUTTON, self.OnBtnAfterSettleButton,
              id=wxID_PANELSALELISTBTNAFTERSETTLE)

        self.cbOrderType = wx.ComboBox(choices=[],
              id=wxID_PANELSALELISTCBORDERTYPE, name=u'cbOrderType',
              parent=self, pos=wx.Point(784, 64), size=wx.Size(145, 27),
              style=wx.CB_DROPDOWN | wx.CB_READONLY, value=u'')
        self.cbOrderType.SetLabel(u'')
        self.cbOrderType.Bind(wx.EVT_COMBOBOX, self.OnCbOrderTypeCombobox,
              id=wxID_PANELSALELISTCBORDERTYPE)

    def __init__(self, parent, type):
        self._init_ctrls(parent)
        
        self.type = type
        self.myInit()
    
    def __init_nb(self):
              
        self.nb.AddPage(imageId=-1, page=self.lcContent, select=True,
                    text=u'产品明细')
        
        self.lcVoucherList = MyListCtrlOrderVoucherList(self.nb)
        self.nb.AddPage(imageId=-1, page=self.lcVoucherList, select=False,
                    text=u'付款明细')
        
        if (self.type == Type_Sale):
            self.lcVoucherList.setOrderStyle(CDataCustomer) 
            self.checkBox_unpaid.Show()
            self.checkBox_not_delivery.Show()
            self.cbOrderType.Show()
        else:
            self.lcVoucherList.setOrderStyle(CDataSupplier)
            self.checkBox_unpaid.Hide()
            self.checkBox_not_delivery.Hide()
            self.cbOrderType.Hide()
               
    def myInit(self):
        self.dateStart.SetValue(wx.DateTime.Today())
        self.dateEnd.SetValue(wx.DateTime.Today())
        
        self.m_peer = None
        self.tcPeerName.SetFocus()
        
        self.splitterWin = MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        self.nb = wx.Notebook(parent=self.splitterWin)
        
        
        if(self.type == Type_Sale):
            #self.TPeer.SetLabel(u'客户名称')
            self.popupWin = DlgCustomerChoice.create(self)
            self.lcBill = MyOrderListCtrl(self.splitterWin)
            self.lcContent = MyOrderContentListCtrl(self.nb)
            
        elif(self.type == Type_Pur):
            self.popupWin = DlgPopupSupplier.create(self)
            self.lcBill = MyListCtrlPurOrder(self.splitterWin)
            self.lcContent = MyListCtrlPurContent(self.nb)
        
        self.tcPeer = MyPopupTextCtrlDecorator(self.tcPeerName, self.popupWin)
        
        self.cbPioneer = MyComboBoxDecorator(self.comboBoxPioneer, CDataStaff, CDataStaff.COL_NAME, only_enable_staff)
        self.cbPioneer.refresh()

        #self.lcBill.SetSize(wx.Size(1000, 250))
        #self.lcBill.Move(wx.Point(22,100))
        self.lcBill.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnBillListItemSelected)
        
        #self.lcContent.Move(wx.Point(22,365))
        #self.lcContent.SetSize(wx.Size(950, 250))
        self.__init_nb()
        
        self.lcBill.SetMinSize(wx.Size(950, 50))
        self.splitterWin.AppendWindow(self.lcBill, 250)
        
        self.nb.SetMinSize(wx.Size(950, 50))
        self.splitterWin.AppendWindow(self.nb)
        
        self.splitterWin.Move(wx.Point(22, 100))
        # 设置大小为什么必须放在最后？放在AppendWindow之前导致sashPos参数不起作用
        self.splitterWin.SetSize(wx.Size(1000, 500))
        self.splitterWin.SetOrientation(wx.VERTICAL)
        self.splitterWin.SizeWindows()

        self._initChoice()
        self.checkBox_not_delivery.Hide()

    def _initChoice(self):
        self.showAll = self.cbOrderType.Append(u'全部')
        self.showTong = self.cbOrderType.Append(u'仅同莱创')
        self.showYi = self.cbOrderType.Append(u'仅易天达')
        self.showTongYi = self.cbOrderType.Append(u'仅同莱创和易天达')
        self.showNoTongYi = self.cbOrderType.Append(u'非同莱创和易天达')
        self.showNoSend = self.cbOrderType.Append(u'自提与发货')
        self.cbOrderType.SetSelection(self.showAll)
        
        self.showState = {self.showAll:'all'
            , self.showTong:'tong'
            , self.showYi:'yi'
            , self.showTongYi:'tongyi'
            , self.showNoTongYi:'notongyi'
            , self.showNoSend:'nosend'}
        
    def setCustomer(self, obj):
        self.setSelectPeer(obj)
        
    def setSelectObj(self, obj):
        self.setSelectPeer(obj)
            
    def setSelectPeer(self, obj):
        if (obj is not None): 
            self.m_peer = obj
            self.tcPeer.ChangeValue(obj.getValue(obj.COL_NAME))
        
    def getSelectPeer(self):
        return self.m_peer 
                                        
    def OnBillListItemSelected(self, event):
        '''按照选中订单，显示订单内容'''
        item = self.lcBill.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        #orderId = self.orderList.GetItem(item, self.orderList.COL_ID).GetText()
        billId = self.lcBill.getBillId(item)
        self.lcContent.refresh({'billId':billId})
        self.lcVoucherList.refresh({'billId':billId})
        
    def OnBtnOneDayButton(self, event):
        self.dateStart.SetValue(wx.DateTime.Today())
        self.dateEnd.SetValue(wx.DateTime.Today())

    def OnBtnOneWeekButton(self, event):
        day = wx.DateTime.Today()
        self.dateEnd.SetValue(day)
        
        span = wx.DateSpan.Days(7)
        day.SubtractDS(span)
        self.dateStart.SetValue(day)
        

    def OnBtnOneMonthButton(self, event):
        day = wx.DateTime.Today()
        self.dateEnd.SetValue(day)
        
        span = wx.DateSpan.Months(1)
        day.SubtractDS(span)
        self.dateStart.SetValue(day)

    def OnBtnOneYearButton(self, event):
        day = wx.DateTime.Today()
        self.dateEnd.SetValue(day)
        
        span = wx.DateSpan.Years(1)
        day.SubtractDS(span)
        self.dateStart.SetValue(day)

    def OnBtnAllDateButton(self, event):
        self.dateEnd.SetValue(wx.DateTime.Today())        
        self.dateStart.SetValue(wx.DateTimeFromDMY(1,0,2000,0,0,00))

    def OnBtnDayBeforeButton(self, event):
        day = self.dateEnd.GetValue()        
        span = wx.DateSpan.Days(1)
        day.SubtractDS(span)
        self.dateEnd.SetValue(day)
        self.dateStart.SetValue(day)

    def OnBtnDayAfterButton(self, event):
        day = self.dateEnd.GetValue()        
        span = wx.DateSpan.Days(1)
        day.AddDS(span)
        self.dateEnd.SetValue(day)
        self.dateStart.SetValue(day)
        
    def OnBtnSearchButton(self, event):
        '''按照搜索条件，显示订单信息'''
        if self.tcPeer.GetValue() == '':
            #self.tcPeer.ChangeValue(u'全部客户')
            self.m_peer = None
            
            # 时间跨度大应提示时间长
            span = self.dateEnd.GetValue() - self.dateStart.GetValue()
            if span.GetDays() > 31:
                msg = u'没有选择单位，时间跨度较大，可能比较耗时，是否确认查询？'
                dlg = wx.MessageDialog(self, msg, u'提示消息', wx.YES_NO|wx.ICON_QUESTION)
                if dlg.ShowModal() != wx.ID_YES:
                    return

                # b_boss = conf.getint('permission', 'boss', 0)
                # if (b_boss !=1):
                #     return
                if not PermitManager.accessTest(const.PERMIT_MODIFY_ORDER):
                    return
            
        filter = {'dateStart':self.dateStart.GetValue().Format('%Y-%m-%d'),
                    'dateEnd':self.dateEnd.GetValue().Format('%Y-%m-%d')}
                
        if self.m_peer is not None:
            filter['peerId'] = self.m_peer.getValue(self.m_peer.COL_ID)
            filter['peerName'] = self.m_peer.getValue(self.m_peer.COL_NAME)
        
        pioneerObj = self.cbPioneer.getSelectObj()
        if pioneerObj is not None:
            filter['pioneerId'] = pioneerObj.getValue(CDataStaff.COL_ID)

        filter['show'] = self.showState[self.cbOrderType.GetSelection()] 

        if(self.type == Type_Sale):
            self.lcBill.SetShowMode(self.checkBox_unpaid.GetValue(),
                self.checkBox_not_delivery.GetValue())
                            
        cnt = self.lcBill.refresh(filter)
        if (cnt == 0):
            dlg = wx.MessageDialog(self, u'没有符合条件的记录', u'提示消息', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
   
    def OnBtnPopupPeerButton(self, event):
        self.tcPeer.resetPopupWinPos()
        self.popupWin.Show() 

    def OnBtnExportListButton(self, event):
        dlg = wx.TextEntryDialog(self, u'请输入文件名，注意如果当前目录下存在同名文件，该同名文件将被覆盖',
                                u'提示',u'销售单.xls',wx.OK|wx.CANCEL|wx.CENTRE)
        if dlg.ShowModal() != wx.ID_OK:
            return
        file = dlg.GetValue()
        
        if(kit.exportList(self.lcBill, file) < 0):
            msg = u'数据导出失败，请查看是不是其他程序中打开了该文件！'
        else:
            msg = u'数据完成导出'
            
        dlg = wx.MessageDialog(self, msg, u'提示',wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()

    def OnBtnPrintButton(self, event):
        import MyPrinter
        item = self.lcBill.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if(item == -1):
            dlg = wx.MessageDialog(self, u'请先选择要打印的订单',
                            u'提示消息', wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
             
        orderId = self.lcBill.getBillId(item)
        
        if(self.type == Type_Sale):
            MyPrinter.MyPrinter.printSaleOrder(self, orderId)
        else:
            dlg = wx.MessageDialog(self, u'尚未实现该功能', u'提示消息', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal() 

    def OnCheckBox_unpaidCheckbox(self, event):
        self.OnBtnSearchButton(event) 

    def OnCheckBox_not_deliveryCheckbox(self, event):
        self.OnBtnSearchButton(event) 

    def search_by_peer(self, peerObj):
        self.setSelectObj(peerObj)
        self.OnBtnOneYearButton(None)
        self.OnBtnSearchButton(None)

    def OnBtnClearButton(self, event):
        self.tcPeerName.SetValue("")
        self.tcPeerName.SetFocus()

    def OnBtnAfterSettleButton(self, event):
        if self.m_peer is None:
            dlg = wx.MessageDialog(self, u'请先选择客户',
                            u'提示消息', wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        self.dateEnd.SetValue(wx.DateTime.Today())
        date = self.m_peer.getValue(CDataCustomer.COL_SETTLE_DATE)
        if isinstance(date, unicode) or isinstance(date, str):
            date = kit.str2Date(date)
        self.dateStart.SetValue(wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0) 
            if date
            else wx.DateTimeFromDMY(1,0,2000,0,0,00))
        self.checkBox_not_delivery.SetValue(False)
        self.checkBox_unpaid.SetValue(True)
        self.OnBtnSearchButton(event) 

    def OnCbOrderTypeCombobox(self, event):
        self.OnBtnSearchButton(event) 
